var router = require('express').Router();
var util = require('util');
var uuid = require('node-uuid');
var cookie = require('cookie');
var LRU = require("lru-cache");
var EventProxy = require("eventproxy");
var async = require("async");


var Consts = require('../consts');
var resultJson = require('../result-json');
var Utils = require('../utils');
var logger = require('../models/logger');
var User = require('../models/User');
var Course = require('../models/Course');
var Project = require('../models/Project');
var Teacher = require('../models/Teacher');
var nodeExcel = require('../xls-export');
var CryptoJS = require("../CryptoJS");
var SMSSend = require('../sms-utils');


var options = {
		max: 500,
		maxAge: 1000 * 60 * 60
	},
	cache = LRU(options);

router.post('/', function(req, res) {
	res.send('respond with a resource');
});

//lgnout
router.post("/out", function(req, res) {
	var cookies = [cookie.serialize(Consts.COOKIE.COOKIE_CODE, "", {
		maxAge: Consts.COOKIE.MAXAGE,
		path: "/"
	})];
	res.setHeader("Set-cookie", cookies);
	return res.send(resultJson(0));
})

//学生学习
router.post("/study", function(req, res) {
	var courseId = req.body.courseId; //课程id
	var chapterId = req.body.chapterId; //章节id
	var knowledgeId = req.body.knowledgeId; //知识点id 
	var user = JSON.parse(JSON.stringify(req.body._user));
	if (!courseId || !chapterId || !knowledgeId)
		return res.send(resultJson(3));
	Course.findOne({
		"chapter._id": chapterId
	}, {
		"chapter.$": 1
	}).exec(function(err, course) {
		if (err)
			return res.send(resultJson(2));
		var knowledge = [];
		var oldknowledge = [];
		var ni = -1;
		var nj = -1;
		if (user.course) {
			ni = user.course.find(courseId, "_id");
			if (ni >= 0) {
				nj = user.course[ni].chapter.find(chapterId, "_id");
				if (nj >= 0) {
					oldknowledge = user.course[ni].chapter[nj].knowledge;
				} else {
					user.course[ni].chapter.push({
						_id: chapterId, //章节id
						status: Consts.CHAPTERSTATUS.UNOVER, //章节状态 未学习  未完成  完成
						knowledge: [knowledgeId]
					});
				}
			} else {
				user.course.push({
					_id: courseId, //课程id
					create: new Date, //选课时间
					finish: false, //完成状态
					chapter: [{
						_id: chapterId, //章节id
						status: Consts.CHAPTERSTATUS.UNOVER, //章节状态 未学习  未完成  完成
						knowledge: [knowledgeId]
					}]
				});
			}
		} else {
			user.course = [{
				_id: courseId, //课程id
				create: new Date, //选课时间
				finish: false, //完成状态
				chapter: [{
					_id: chapterId, //章节id
					status: Consts.CHAPTERSTATUS.UNOVER, //章节状态 未学习  未完成  完成
					knowledge: [knowledgeId]
				}]
			}]
		}
		for (var i = 0; i < course.chapter[0].knowledge.length; i++) {
			knowledge.push(course.chapter[0].knowledge[i]._id)
		};
		var flag = true;
		oldknowledge.push(knowledgeId);
		oldknowledge = oldknowledge.unique();
		knowledge = knowledge.unique();
		for (var i = 0; i < knowledge.length; i++) {
			if (oldknowledge.find(knowledge[i]) < 0) {
				flag = false;
			}
		};
		if (ni >= 0 && nj >= 0) {
			if (flag) {
				user.course[ni].chapter[nj].status = Consts.CHAPTERSTATUS.OVER;
			} else
				user.course[ni].chapter[nj].status = Consts.CHAPTERSTATUS.UNOVER;
			user.course[ni].chapter[nj].knowledge = user.course[ni].chapter[nj].knowledge.unique();
		}
		User.update({
			_id: user._id
		}, {
			$set: user
		}).exec(function(err) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			res.send(resultJson(0));
		})
	});
});

//查询当前用户的 课程和项目
router.post("/getCourseProject", function(req, res) {
	var _id = req.body._id || req.body._user._id;
	User.findById(_id, {
		course: 1,
		project: 1
	}).exec(function(err, user) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		if (!user)
			user = {};
		user = JSON.parse(JSON.stringify(user));
		user.courseList = [];
		if (req.body.field == "course") {
			var result = []
			async.each(user.course, function(item, cb) {
				Course.findById(item._id).exec(function(err, course) {
					if (err)
						return cb(err);
					if (!course)
						course = {};
					result.push({
						_id: course._id,
						name: course.name
					});
					cb();
				});
			}, function(err) {
				if (err) {
					logger.error(err);
					return res.send(resultJson(2));
				}
				res.send(resultJson(0, result));
			});
		} else {
			var courseId = [],
				projectId = []
			if (user.course)
				for (var i = 0; i < user.course.length; i++) {
					courseId.push(user.course[i]._id);
				};
			if (user.project)
				for (var i = 0; i < user.project.length; i++) {
					projectId.push(user.project[i]._id);
				};
			async.parallel({
				courses: function(areascb) {
					// 查询所在地区
					Course.find({
						_id: {
							$in: courseId
						}
					}, {
						_id: 1,
						name: 1,
						create: 1,
						desc: 1,
						photo: 1,
						classHour: 1
					}, function(err, area) {
						areascb(err, area);
					});
				},
				projects: function(postscb) {
					// 查询岗位
					Project.find({
						"_id": {
							$in: projectId
						}
					}, {
						_id: 1,
						name: 1,
						create: 1,
						desc: 1,
						picture: 1
					}, function(err, posts) {
						postscb(err, posts);
					});
				}
			}, function(err, results) {
				console.log(results)
				if (err) {
					logger.error(err);
					return res.send(resultJson(2));
				}
				user.course = [];
				user.project = [];
				user.course = results.courses;
				user.project = results.projects;
				res.send(resultJson(0, user));
			});
		}



	});
});

//设置当前用户的 课程和项目
router.post("/setCourseProject", function(req, res) {
	var _id = req.body._id || req.body._user._id;
	var field = req.body.field; // course  project
	var value = req.body.value; //课程或项目的id
	if (!value)
		return res.send(resultJson(3));
	if (field == "course") {
		var item = {
			$addToSet: {
				"course": {
					_id: value,
				}
			}
		}
		User.update({
			_id: _id
		}, item).exec(function(err) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			res.send(resultJson(0));
		});
	} else if (field == "project") {
		Project.findById(value).exec(function(err, project) {
			if (err)
				return res.send(resultJson(2));
			if (!project)
				project = {};
			var courses = project.course || [];
			User.update({
				_id: _id
			}, {
				$addToSet: {
					"project": {
						_id: value,
					}
				}
			}).exec(function(err) {
				if (err) {
					return res.send(resultJson(2));
				}
				async.each(courses, function(course, cb) {
					var item = {
						$addToSet: {
							"course": {
								_id: course,
							}
						}
					}
					console.log(item, value);
					User.update({
						_id: _id
					}, item).exec(function(err) {
						if (err) {
							return cb(err);
						}
						cb();
					});
				}, function() {
					if (err) {
						logger.error(err);
						return res.send(resultJson(2));
					}
					res.send(resultJson(0));
				});
			});

		});
	} else {
		return res.send(resultJson(3));
	}

});

router.post('/findPwd', function(req, res) {
	var value = req.body.value;
	var field = req.body.field;
	var code = Utils.random();
	if (field == "email") {
		var email = value,
			subject = "重置密码",
			text = "",
			html = "你重置密码的验证码是：";
		if (!email)
			return res.send(resultJson(3));

		User.findOne({
			email: email
		}, function(err, user) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			if (!user)
				return res.send(resultJson(111));

			html += code;
			Utils.mailSend(email, subject, text, html, function(err, result) {
				if (err) {
					logger.error(err);
					return res.send(resultJson(104));
				}
				cache.set(email, code);
				console.log(email, cache.get(email))
				res.send(resultJson(0));
			})
		})
	} else if (field == "phone") {
		var phone = value;
		var text = "重置密码" + code;
		if (!phone)
			return res.send(resultJson(3));

		User.findOne({
			phone: phone
		}, function(err, user) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			if (!user)
				return res.send(resultJson(101));
			phone = [phone];
			SMSSend.NoticeSms(phone, text, function(result) {
				cache.set(phone, code);
				console.log(phone, cache.get(phone))
				res.send(resultJson(result));
			});
		})
	} else
		return res.send(resultJson(3));
});

//重复验证  手机号  邮箱  用户名
router.post("/check", function(req, res) {
	var value = req.body.value;
	User.find({
		$or: [{
			email: value
		}, {
			phone: value
		}, {
			username: value
		}],
	}).count(function(err, num) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		res.send(resultJson(0, num));
	});
});


//注册
router.post('/reg', function(req, res) {
	var user = req.body;
	user.category = user.category || Consts.UTYPE.STUDENT;
	if (!user.username || !user.password)
		return res.send(resultJson(3));

	user.password = Utils.MD5(user.password);
	console.log(req.body);
	var item = {
		$or: []
	}
	if (user.email) {
		item.$or.push({
			phone: user.email
		});
		item.$or.push({
			email: user.email
		});
		item.$or.push({
			username: user.email
		});
	}
	if (user.phone) {
		item.$or.push({
			phone: user.phone
		});
		item.$or.push({
			email: user.phone
		});
		item.$or.push({
			username: user.phone
		});
	}
	if (user.username) {
		item.$or.push({
			phone: user.username
		});
		item.$or.push({
			email: user.username
		});
		item.$or.push({
			username: user.username
		});
	}
	User.find(item, function(err, users) {
		if (err)
			return res.send(resultJson(2));
		var length = users && users.length || 0;
		for (var i = 0; i < length; i++) {
			if (users[i].username == user.username || users[i].phone == user.username || users[i].email == user.username) {
				return res.send(resultJson(105));
			}
			if (user.phone)
				if (users[i].username == user.phone || users[i].phone == user.phone || users[i].email == user.phone) {
					return res.send(resultJson(106));
				}
			if (user.email)
				if (users[i].username == user.email || users[i].phone == user.email || users[i].email == user.email) {
					return res.send(resultJson(107));
				}
		};
		var newUser = new User(user);
		newUser.status = Consts.STATUS.NORMAL;
		newUser.save(function(err) {
			if (err)
				return res.send(resultJson(2));
			return res.send(resultJson(0, newUser));
		});
	});
});

router.post('/detail', function(req, res) {
	var _id = req.body._id;
	if (!_id)
		return res.send(resultJson(3));

	User.findOne({
		_id: _id
	}).exec(function(err, user) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		return res.send(resultJson(0, user));
	});
});

router.post('/lgn', function(req, res) {
	var value = req.body.value; // username  phone  email 
	var pwd = req.body.pwd;
	if (!value || !pwd) {
		logger.error("参数错误：");
		return res.send(resultJson(3));
	}
	User.find({
		$or: [{
			email: value
		}, {
			phone: value
		}, {
			username: value
		}],
		password: Utils.MD5(pwd),
		status: Consts.STATUS.NORMAL
	}, function(err, users) {
		if (err || users.length > 1 || users.length == 0) {
			var cookies = [cookie.serialize(Consts.COOKIE.COOKIE_CODE, "", {
				maxAge: Consts.COOKIE.MAXAGE,
				path: "/"
			})];
			res.setHeader("Set-cookie", cookies);
			logger.error(err);
			return res.send(resultJson(100));
		} else {
			users = JSON.parse(JSON.stringify(users));
			var token = Utils.MD5("" + users[0]._id);
			User.update({
				_id: users[0]._id
			}, {
				$set: {
					token: token
				}
			}, function(err) {
				if (err) {
					logger.error(err);
					return res.send(resultJson(2));
				}
				console.log(token, "token");
				var cookies = [cookie.serialize(Consts.COOKIE.COOKIE_CODE, token, {
					maxAge: Consts.COOKIE.MAXAGE,
					path: "/"
				})];
				res.setHeader("Set-cookie", cookies);
				return res.send(resultJson(0, users));
			})
		}
	});
});

//验证接口
router.post('/confirmation', function(req, res) {
	User.find({
		token: req.cookies[Consts.COOKIE.COOKIE_CODE]
	}, function(err, user) {
		if (err || !user)
			return res.send(resultJson(999));

		var cookies = [cookie.serialize(Consts.COOKIE.COOKIE_CODE, req.cookies[Consts.COOKIE.COOKIE_CODE], {
			maxAge: Consts.COOKIE.MAXAGE,
			path: "/"
		})]
		res.setHeader("Set-cookie", cookies);
		res.send(resultJson(0, user));
	});
});

//获取某类型的用户
router.post('/list', function(req, res) {
	var proxy = new EventProxy();
	proxy.all("results", "count", function(results, count) {
		res.send(resultJson(0, {
			results: results,
			count: count
		}))
	})
	var start = req.body.start || 0;
	var count = req.body.count || Consts.MAX;
	var user = req.body;
	var category = user.category || Consts.UTYPE.STUDENT;
	var from = user._user.category; //不需要前端传值
	var query;
	if (from == Consts.UTYPE.ADMIN || from == Consts.UTYPE.OPERATION) { //平台管理员、课程管理员 查看用户
		query = User.find({
			category: category,
		});
	} else if (from == Consts.UTYPE.PROVIDER || from == Consts.UTYPE.TUTOR) { //课程提供商、辅导老师 通过辅导课程来查看用户
		var ids = new Array();
		for (var i = 0; i < user._user.course.length; i++)
			ids.push(courses[i]._id);
		query = User.find({
			category: category,
			"course.id": {
				"$in": ids
			},
		});
	} else {
		query = User.find({
			category: category,
		});
	}
	query.skip(start).limit(count).sort({
		name: 1
	}).exec(function(err, users) {
		if (err)
			return res.send(resultJson(100));
		proxy.emit("results", users);
	});
	query.count(function(err, num) {
		if (err)
			return res.send(resultJson(100));
		proxy.emit("count", num);
	});
});

router.post('/upsert', function(req, res) {
	var user = req.body;
	var item = {
		$or: []
	}
	if (user.email) {
		item.$or.push({
			phone: user.email
		});
		item.$or.push({
			email: user.email
		});
		item.$or.push({
			username: user.email
		});
	}
	if (user.phone) {
		item.$or.push({
			phone: user.phone
		});
		item.$or.push({
			email: user.phone
		});
		item.$or.push({
			username: user.phone
		});
	}
	if (user.username) {
		item.$or.push({
			phone: user.username
		});
		item.$or.push({
			email: user.username
		});
		item.$or.push({
			username: user.username
		});
	}
	if (user._id) {
		if (!user.phone || !user.username)
			return res.send(resultJson(3));
		item._id = {
			$ne: user._id
		};
		User.find(item).exec(function(err, users) {
			console.log(users, user._id);
			if (err) {
				return res.send(resultJson(2));
			}
			if (users.length != 0)
				return res.send(resultJson(9));
			else
				User.update({
					_id: user._id
				}, {
					$set: user
				}, function(err) {
					if (err)
						return res.send(resultJson(2));
					return res.send(resultJson(0));
				});
		});
	} else {
		if (!user.phone || !user.username)
			return res.send(resultJson(3));
		var newUser = new User(user);
		User.find(item).exec(function(err, users) {
			if (err) {
				return res.send(resultJson(2));
			}
			if (users.length != 0)
				return res.send(resultJson(9));
			else
				newUser.save(function(err) {
					if (err)
						return res.send(resultJson(2));
					return res.send(resultJson(0, newUser));
				});
		});

	}
});

router.post("/updatephoto", function(req, res) {
	req.query.updatephoto = true;
	Utils.upload(req, function(json) {
		if (json.code)
			return res.send(resultJson(json.code));

		User.update({
			_id: req.query.id
		}, {
			$set: {
				photo: json.result.url
			}
		}, function(err) {
			if (err)
				return res.send(resultJson(2));
			return res.send(resultJson(0, {
				url: json.result.url
			}));
		});
	});
});

//重置密码
router.post('/resetPassword', function(req, res) {
	var user = req.body;
	var password = user.password;
	var code = user.code;
	var value = user.value;
	var field = user.field;
	if (!value || !code || !password)
		return res.send(resultJson(3));
	if (code == cache.get(value)) {
		var item = {};
		if (field == "phone") {
			item = {
				phone: value
			}
		} else if (field == "email") {
			item = {
				email: value
			}
		} else
			return res.send(resultJson(3));
		User.update(item, {
			$set: {
				password: Utils.MD5(password)
			}
		}, function(err) {
			if (err)
				return res.send(resultJson(2));
			return res.send(resultJson(0));
		});
	} else
		return res.send(resultJson(7));

});

//修改密码
router.post('/updatePassword', function(req, res) {
	var user = req.body;
	var _id = user._id;
	var password = user.password;
	var oldPassword = user.oldPassword;
	if (!_id || !password)
		return res.send(resultJson(3));

	User.update({
		_id: _id,
		password: Utils.MD5(oldPassword)
	}, {
		$set: {
			password: Utils.MD5(password)
		}
	}, function(err, result) {
		if (err)
			return res.send(resultJson(2));
		if (result.n > 0)
			return res.send(resultJson(0, Utils.MD5(password)));
		else
			return res.send(resultJson(8));
	});
});

router.post('/remove', function(req, res) {
	var _id = req.body._id;
	if (!_id)
		return res.send(resultJson(3));
	Teacher.count({
		owner: _id
	}).exec(function(err, num) {
		if (num > 0) {
			return res.send(resultJson(108));
		}
		Course.count({
			owner: _id
		}).exec(function(err, num) {
			if (num > 0) {
				return res.send(resultJson(108));
			}
			Project.count({
				owner: _id
			}).exec(function(err, num) {
				if (num > 0) {
					return res.send(resultJson(108));
				}
				User.remove({
					_id: _id
				}, function(err) {
					if (err)
						return res.send(resultJson(2));
					return res.send(resultJson(0));
				});
			});
		});
	});
});

router.get('/exportUser', function(req, res) {
	var category = req.query.category || Consts.UTYPE.STUDENT;

	var conf = {};
	var title1 = "用户导出表";
	conf.heads = [title1];
	conf.cols = [{
		caption: '序号',
		type: 'number',
	}, {
		caption: '账号',
		type: 'string',
	}, {
		caption: '姓名',
		type: 'string',
	}, {
		caption: '性别',
		type: 'string',
	}, {
		caption: '身份证号',
		type: 'string',
	}, {
		caption: '手机号',
		type: 'string',
		width: 20
	}, {
		caption: '联系地址',
		type: 'string'
	}, {
		caption: '企业名称',
		type: 'string'
	}];

	conf.rows = [];
	User.find({
		category: category
	}, function(err, users) {
		if (err)
			return res.send(resultJson(2));

		var filename = "用户导出表.xlsx";
		filename = encodeURI(filename);
		exportUserCb(0, users, conf, res, filename);
	});
});

function exportUserCb(index, users, conf, res, filename) {
	if (index == users.length || users.length == 0) {
		var result = nodeExcel.execute(conf);
		res.setHeader('Content-Type', 'application/vnd.openxmlformats');
		res.setHeader("Content-Disposition", "attachment; filename=" + filename);
		return res.end(result, 'binary');
	}

	var outputs = [];
	var address = users[index].express && users[index].express.addr || "";
	outputs.push(index, users[index].email || "", users[index].name || "", users[index].sex || "", users[index].scard || "",
		users[index].phone || "", address, users[index].company || "");
	conf.rows.push(outputs);

	index++;
	exportUserCb(index, users, conf, res, filename);
}

module.exports = router;